import axios, {AxiosResponse} from 'axios'
import {
    ElMessage
} from 'element-plus';
import config from "@/aixos/env/config";

export const request = (options: any) => {
    return new Promise((resolve, reject) => {

        const service = axios.create({
            baseURL: config.VUE_APP_BASE_URL,
            timeout: 80000,// request timeout
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        })

        // 请求拦截
        axios.interceptors.request.use((config: any) => {
            const token = JSON.stringify(localStorage.getItem('token'));
            if (token) {
                config.headers.Authorization = token
            }
            //若请求方式为post，则将data参数转为JSON字符串
            if (config.method === 'POST') {
                config.data = JSON.stringify(config.data);
            }
            return config
        }, (error: any) => {
            return Promise.reject(error)
        })

        // 响应拦截
        axios.interceptors.response.use((response: AxiosResponse) => {
            return response.data
        }, (error: any) => {
            if (error.response && error.response.status) {
                const status = error.response.status
                let message
                switch (status) {
                    case 400:
                        message = '请求错误';
                        break;
                    case 401:
                        message = '没有权限';
                        break;
                    case 402 || 403:
                        message = '服务器拒绝  token过期';
                        break;
                    case 404:
                        message = '请求地址出错';
                        break;
                    case 408:
                        message = '请求超时';
                        break;
                    case 500:
                        message = '服务器内部错误!';
                        break;
                    case 501:
                        message = '服务未实现!';
                        break;
                    case 502:
                        message = '网关错误!';
                        break;
                    case 503:
                        message = '服务不可用!';
                        break;
                    case 504:
                        message = '网关超时!';
                        break;
                    case 505:
                        message = 'HTTP版本不受支持';
                        break;
                    default:
                        message = '请求失败'
                }
                ElMessage.error(message);
                return Promise.reject(error);
            }
            return Promise.reject(error)
        })

        // 请求处理
        service(options)
            .then((res) => {
                resolve(res)
            })
            .catch((error) => {
                reject(error)
            })
    })
}


export default request
